package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"oct-test10/models"
	"oct-test10/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败，用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.MD5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}

func AddRle(c *gin.Context) {
	RoleID, _ := strconv.Atoi(c.PostForm("RoleID"))
	Uid, _ := strconv.Atoi(c.PostForm("uid"))
	var role models.Role
	tx := models.DB.Begin()
	tx.Where("id = ?", RoleID).First(&role)
	tx.Model(&models.Role{}).Update("uid", gorm.Expr("uid = ?", Uid))
	tx.Save(role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色分配成功",
	})
	return
}

func AddQuite(c *gin.Context) {
	RoleID, _ := strconv.Atoi(c.PostForm("RoleID"))
	Qid, _ := strconv.Atoi(c.PostForm("qid"))
	var role models.Role
	tx := models.DB.Begin()
	tx.Where("id = ?", RoleID).First(&role)
	tx.Model(&models.Role{}).Update("uid", gorm.Expr("qid = ?", Qid))
	tx.Save(role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "权限分配成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var user []models.User
	models.DB.Offset(offset).Limit(size).Find(&user).Order(" username DESC")
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
	})
	return
}
